package com.itheima.mm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mm.dto.R;
import com.itheima.mm.pojo.*;
import com.itheima.mm.pojo.subject_manage.SimpleSubjects;
import com.itheima.mm.pojo.subject_manage.Subjects;
import com.itheima.mm.service.SubjectsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/subjects")
public class SubjectsController {
    @Autowired
    private SubjectsService subjectsService;
    //修改学科
    @PutMapping("/{id}")
    public R modify(@RequestBody Subjects subjects){
        subjectsService.updateById(subjects);
        R r=new R();
        r.setSuccess(true);
        return r;
    }
    //删除学科
    @DeleteMapping("/{id}")
    public R del(@RequestBody Subjects subjects){
        subjectsService.removeById(subjects);
        R r=new R();
        r.setSuccess(true);
        return r;
    }
    //添加学科
    @PostMapping
    public R add(@RequestBody Subjects subjects){
        subjects.setCreatorId(1);
        subjects.setAddDate(LocalDateTime.now());
        subjects.setTags(1);
        subjectsService.save(subjects);
        subjects.setTotals(1);
        R r=new R();
        LambdaQueryWrapper<Subjects> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Subjects::getSubjectName,subjects.getSubjectName());
        r.setId(subjectsService.getOne(wrapper).getId());
        return  r;
    }
    //学科简单列表
    @GetMapping("/simple")
    public List<SimpleSubjects> simpleSubjects(){
        List<Subjects> subjects = subjectsService.list();
        List<SimpleSubjects> list=new ArrayList<>();
        for (Subjects subject : subjects) {
            SimpleSubjects simpleSubjects=new SimpleSubjects();
            simpleSubjects.setValue(subject.getId());
            simpleSubjects.setLabel(subject.getSubjectName());
            list.add(simpleSubjects);
        }
        return list;
    }
    //学科详情
    @GetMapping("/{id}")
    public Subjects selectById(@PathVariable Integer id){
        Subjects subjects = subjectsService.getById(id);
        return subjects;
    }

    //学科列表
    @GetMapping
    public PageResult page(String subjectName,Integer page,Integer pagesize){
        LambdaQueryWrapper<Subjects> wrapper=new LambdaQueryWrapper<>();
        if (subjectName!=null)
            wrapper.like(Subjects::getSubjectName,subjectName);
        IPage<Subjects> p=new Page<>(page,pagesize);
        IPage<Subjects> pg = subjectsService.page(p, wrapper);
        return new PageResult(pg.getTotal(),pg.getSize(),pg.getPages(),pg.getCurrent(),pg.getRecords());
    }


}
